package com.gyg.threadPool;

import lombok.extern.slf4j.Slf4j;

import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author GYG
 */
@Slf4j
public class scheduledThreadPoolTest {
    public static void main(String[] args) {
        //延时任务
        //delayPerform();
        //定时任务1
        //scheduleAtFixedRateMethod();
        //定时任务2
        //scheduleWithFixedDelayMethod();
        scheduledTaskTest();
    }

    /**
     * 任务延时执行
     */
    public static void delayPerform() {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);
        log.info("start...");
        pool.schedule(() -> {
            log.info("test1");
        }, 1, TimeUnit.SECONDS);

        pool.schedule(() -> {
            log.info("test2");
        }, 2, TimeUnit.SECONDS);
    }

    /**
     * 任务定时执行，以上一个任务开始执行算起
     */
    public static void scheduleAtFixedRateMethod() {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        log.info("start...");
        pool.scheduleAtFixedRate(() -> {
            log.info("runing...");
            //线程执行时间大于调度间隔时间
            //Thread.sleep(3000);
        }, 3, 1, TimeUnit.SECONDS);
    }

    /**
     * 任务定时执行，真实的时间间隔，以删一个任务执行结束算起
     */
    public static void scheduleWithFixedDelayMethod() {
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        log.info("start【scheduleWithFixedDelayMethod】...");
        pool.scheduleWithFixedDelay(() -> {
            log.info("runing...");
            //线程执行时间大于调度间隔时间
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, 3, 1, TimeUnit.SECONDS);
    }


    /**
     * 定时任务应用，每周五晚上八点执行
     */
    public static void scheduledTaskTest() {
        //获取到当前时间
        LocalDateTime now = LocalDateTime.now();
        //获取到本周五晚八点
        LocalDateTime time = now.withHour(20).withMinute(0).withSecond(0).withNano(0).with(DayOfWeek.FRIDAY);
        System.out.println(time);
        //当前时间和指定时间比较，当前时间大于比较时间返回正数，否则返回负数
        System.out.println(now.compareTo(time));
        if (now.compareTo(time) > 0) {
            //指定时间加一周
            time = time.plusWeeks(1);
        }
        System.out.println(now);
        System.out.println(time);

        //相差的时间间隔
        long initialDelay = Duration.between(now, time).toMillis();
        System.out.println("当前时间距离指定时间：" + initialDelay);
        //一周的毫秒数
        long period = 1000 * 60 * 60 * 24 * 7;
        ScheduledExecutorService pool = Executors.newScheduledThreadPool(1);
        pool.scheduleAtFixedRate(() -> {
            log.info("task run...");
        }, initialDelay, period, TimeUnit.MILLISECONDS);

    }

}
